package com.album.activity.pageView;


import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.album.R;
import com.album.activity.MessageDialog;
import com.album.activity.SetstateManager;
import com.album.activity.page.Page;
import com.album.activity.page.PageManager;
import com.album.bean.AlbumInfo;
import com.album.bean.Picinfo;
import com.album.common.VerticalSeekBar;
import com.album.provider.ProviderUtil;
import com.album.task.GetPicinfoTask;
import com.album.task.ICallBack;
import com.album.task.Task;
import com.album.utils.CommonUtil;
import com.album.utils.MyLog;
import com.google.gson.Gson;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MyPicinfoView extends Page {
	private Context context;
	private LinearLayout linearLayout; 
	private LinearLayout glinearLayout; 
	

	private Gallery gallery;
	private TextView textview01;
	private TextView textview02;
	private com.album.common.VerticalSeekBar seek;

	private Gson gson;
	private static final int PICINFO = 11;
	private static final int PICINFO_FAIL = 12;
	private static final int TIME_OUT = 13;
	private static final int INTERERROR = 14;
	private ProgressDialog dialog_1;
	private String userName;
	private String pic;
	private boolean flag; //标志是否获取信息成功
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	public MyPicinfoView(PageManager manager) {
		super(manager);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(Object extra) {
		// TODO Auto-generated method stub
		super.onCreate(extra);
		
		//按返回跳转到CasualLookView
		MyLog.info(getClass(), "PicinfoView manager 1:"+manager);
		context = manager.getContext();
		userName = CommonUtil.getUserName(context);
		pic = ProviderUtil.getMyPicinfoId(context);//数据库获取id
		gson = new Gson();
		//获取图片信息
		MyLog.info(getClass(), "picId:"+pic);
		getPicInfo(userName,pic);
		LayoutInflater inflater = LayoutInflater.from(manager.getContext());
		linearLayout = (LinearLayout) inflater.inflate(
				R.layout.mypicpage, null);
		gallery = (Gallery) linearLayout.findViewById(R.id.gallery);
		textview01 = (TextView) linearLayout.findViewById(R.id.TextView01);
		textview02 = (TextView) linearLayout.findViewById(R.id.TextView02);
		seek = (VerticalSeekBar) linearLayout.findViewById(R.id.SeekBar01);
		ImageButton set= (ImageButton) linearLayout.findViewById(R.id.btn_setting);
		ImageButton edit= (ImageButton) linearLayout.findViewById(R.id.btn_edit);
		final CustomDialog cd = new CustomDialog(context);
		cd.setDialog(cd);
		set.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//设置单张图片属性
				 cd.show();
			}
		});
		//长按事件  出现调整亮度功能
		gallery.setOnItemLongClickListener(new OnItemLongClickListener() {  
			  
	        @Override  
	        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,  
	                int arg2, long arg3) {  
	            // TODO Auto-generated method stub  
	        	try {
	        		 MyLog.info(getClass(), "gallery长按事件"); 
	        		 textview01.setVisibility(View.VISIBLE);
	        		 seek.setVisibility(View.VISIBLE);
	 	           // glinearLayout.addView(selectedView);
				} catch (Exception e) {
					e.printStackTrace();
				}
	            return false;  
	        }  
	      });  
		gallery.setOnItemClickListener(new OnItemClickListener() {
			  
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				MyLog.info(getClass(), "gallery点击事件"); 
				textview01.setVisibility(View.GONE);
       		    seek.setVisibility(View.GONE);
	           // 	(selectedView);
			}
		});
		gallery.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return false;
			}
		});
		textview02.setText(1+"/"+SetstateManager.piclist.size());
		ImageAdapter adapter = new ImageAdapter(context,SetstateManager.piclist);
		adapter.notifyDataSetChanged();
		gallery.setAdapter(adapter);
		//final VerticalSeekBar sb = (VerticalSeekBar) selectedView.findViewById(R.id.SeekBar01);  
		// 设置拖动条的初始值和文本框的初始值  
		seek.setMax(100);  
		seek.setProgress(30);  
		
     //设置拖动条改变监听器  
//		seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
//		
//		@Override
//		public void onStopTrackingTouch(SeekBar seekBar) {
//			// TODO Auto-generated method stub
//			
//		}
//		
//		@Override
//		public void onStartTrackingTouch(SeekBar seekBar) {
//			// TODO Auto-generated method stub
//			
//		}
//		
//		@Override
//		public void onProgressChanged(SeekBar seekBar, int progress,
//				boolean fromUser) {
//			MyLog.info(getClass(), "亮度改变");
//			
//		}
//	});
	}
	 //获取单张图片信息
    private boolean getPicInfo(String username,String picId){
   	 Task task = new GetPicinfoTask(context, username, picId,new ICallBack() {
				@Override
				public void CallBack(String imageUrl, Bitmap bm) {
				}
				@Override
				public void CallBack(String rspString) {
					try {
						MyLog.info(getClass(), "jsonData:" + rspString);
						rspString = "[" + rspString + "]";
						JSONArray array = new JSONArray(rspString.toString());
						JSONObject obj = array.getJSONObject(0);
						if (obj.getBoolean("msg")) {
							JSONObject res = obj.getJSONObject("data");
							MyLog.info(getClass(), "jsonData:" + res.toString());
							Picinfo info = gson.fromJson(res.toString(), Picinfo.class);
							Message ms = new Message();
							ms.what = PICINFO;
							ms.obj = info;
							handler.sendMessage(ms);
							MyLog.info(getClass(), "picinfo:" + info.passport);
							MyLog.info(getClass(), "title:" + info.title);
							MyLog.info(getClass(), "type:" + info.typeid);
							MyLog.info(getClass(), "public:" + info.ispublic);
							ProviderUtil.insertOrUpdatePicinfo(manager.getContext(), info);
							flag = true;
						} else {
							AlbumInfo info=new AlbumInfo();
							info.setErrCode(obj.getString("errCode"));
							Message ms = new Message();
							ms.what = PICINFO_FAIL;
							ms.obj = info;
							handler.sendMessage(ms);
							flag = false;
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
				@Override
				public void TimeOut() {
					// TODO Auto-generated method stub
					handler.sendEmptyMessage(TIME_OUT);
				}
				@Override
				public void HttpError(int errorCode) {
					// TODO Auto-generated method stub
					handler.sendEmptyMessage(TIME_OUT);
				}
			});
     dialog_1 = ProgressDialog.show(manager.getContext(), "", manager.getContext().getText(R.string.picinfo_doing), true);
	 dialog_1.setCancelable(true);
	 task.doTask(task);
	 return flag;
    }
    private Handler handler = new Handler() {
  		public void handleMessage(Message msg) {
  			try {
  				switch (msg.what) {
  				case PICINFO:
  					Picinfo info = (Picinfo)msg.obj;
  					ProviderUtil.insertOrUpdatePicinfo(context, info);
  					if (dialog_1 != null && dialog_1.isShowing())
						dialog_1.dismiss();
  					break;
  				case PICINFO_FAIL:
  					if (dialog_1 != null && dialog_1.isShowing())
						dialog_1.dismiss();
					MessageDialog.showToast(manager.getContext(), false, manager.getContext().getString(R.string.picinfo_fail));
  					break;
  				case TIME_OUT:
  					if (dialog_1 != null && dialog_1.isShowing())
						dialog_1.dismiss();
					MessageDialog.showToast(manager.getContext(), false, manager.getContext().getString(R.string.int_timeout));
  					break;
  				case INTERERROR:
  					if (dialog_1 != null && dialog_1.isShowing())
						dialog_1.dismiss();
					MessageDialog.showToast(manager.getContext(), false, manager.getContext().getString(R.string.int_error));
  					break;
  				}
 			} 
  			catch (Exception e) {
 				// TODO: handle exception
 			}
  		}
  		};
	public class ImageAdapter extends BaseAdapter {
		int mGalleryItemBackground;
		private Context mContext;
		private List<Integer> picList;


		public ImageAdapter(Context context,List<Integer> picList) {
			mContext = context;
            this.picList = picList;
			TypedArray a = mContext.obtainStyledAttributes(R.styleable.Gallery1);
			mGalleryItemBackground = a.getResourceId(
					R.styleable.Gallery1_android_galleryItemBackground, 0);
			a.recycle();
		}

		@Override
		public int getCount() {
			return picList.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView i = new ImageView(mContext);
			i.setImageResource(picList.get(position));
			//i.setScaleType(ImageView.ScaleType.FIT_XY);
			textview02.setText(position+"/"+SetstateManager.piclist.size());
			//i.setLayoutParams(new Gallery.LayoutParams(CommonUtil.width, LayoutParams.WRAP_CONTENT));

			// The preferred Gallery item background
			//i.setBackgroundResource(mGalleryItemBackground);

			return i;
		}
		

	}
	@Override
	public View getView() {
		// TODO Auto-generated method stub
		return linearLayout;
	}
	
	private void showExitGameAlert() {
    	final AlertDialog dlg = new AlertDialog.Builder(context).create();
    	dlg.show();
    	Window window = dlg.getWindow();
            // *** 主要就是在这里实现这种效果的.
            // 设置窗口的内容页面
    	window.setContentView(R.layout.pic_setting);
            // 为确认按钮添加事件,执行退出应用操作
    	ImageButton set_bc = (ImageButton) window.findViewById(R.id.pic_set_bc);
    	set_bc.setOnClickListener(new View.OnClickListener() {
    		public void onClick(View v) {
    			  // 保存配置
    		}
    	});
    	
    	ImageButton ok = (ImageButton) window.findViewById(R.id.pic_set_ok);
    	ok.setOnClickListener(new View.OnClickListener() {
    		public void onClick(View v) {
    			  // 确定...
    		}
    	});
     
            // 关闭alert对话框架
//            ImageButton cancel = (ImageButton) window.findViewById(R.id.btn_cancel);
//            cancel.setOnClickListener(new View.OnClickListener() {
//    	  public void onClick(View v) {
//    		dlg.cancel();
//    		}
//    	  });
    }
	
//	@Override
//	public void onCreateContextMenu(ContextMenu menu, View v,
//			ContextMenuInfo menuInfo) {
//		menu.add("Action");
//	}
//
//	@Override
//	public boolean onContextItemSelected(MenuItem item) {
//		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
//				.getMenuInfo();
//		Toast.makeText(this, "Longpress: " + info.position, Toast.LENGTH_SHORT)
//				.show();
//		return true;
//	}

}
